

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// windows
#include "../include/mystdafx.h"
#include "../os/os_mutex.h"

#ifndef WIN32

typedef struct 
{
	pthread_mutex_t hMutex;
}os_mutex_priv_t;


int os_mutex_create(os_mutex_t* m)
{
	os_mutex_priv_t* priv = (os_mutex_priv_t*) malloc(sizeof(os_mutex_priv_t));
	if(!priv) return -1;
	m->pPriv = priv;

	// ´´½¨mutex
	if(pthread_mutex_init(&priv->hMutex, NULL) < 0)
	{
		free(priv);
		m->pPriv = NULL;
		return 0;
	}

	return 1;
}

void os_mutex_destroy(os_mutex_t* m)
{
	if(m->pPriv) 
	{
		os_mutex_priv_t* priv = (os_mutex_priv_t*) m->pPriv;
		pthread_mutex_destroy(&priv->hMutex);
		free(priv);
		m->pPriv = NULL;
	}
}

int os_mutex_lock(os_mutex_t* m)
{
	os_mutex_priv_t* priv = (os_mutex_priv_t*) m->pPriv;
	if(!priv) 
		return 0;

	if( pthread_mutex_lock(&priv->hMutex) < 0)
	{
		return 0;
	}
	return 1;
}

int os_mutex_trylock(os_mutex_t* m)
{
	os_mutex_priv_t* priv = (os_mutex_priv_t*) m->pPriv;
	if(!priv) 
		return 0;

	if(pthread_mutex_trylock(&priv->hMutex) < 0)
	{
		return 0;
	}
	return 1;
}

void os_mutex_unlock(os_mutex_t* m)
{
	os_mutex_priv_t* priv = (os_mutex_priv_t*) m->pPriv;
	if(!priv) return;

	pthread_mutex_unlock(&priv->hMutex);
}

#endif

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// windows

#ifdef WIN32

typedef struct 
{
	CRITICAL_SECTION* hMutex;
}os_mutex_priv_t;


int os_mutex_create(os_mutex_t* m)
{
	os_mutex_priv_t* priv = new os_mutex_priv_t;
	if(!priv) 
		return 0;
	m->pPriv = priv;

	priv->hMutex = new CRITICAL_SECTION;
	InitializeCriticalSection( priv->hMutex );
	if(priv->hMutex == NULL)
	{
		delete priv;
		m->pPriv = NULL;
		return 0;
	}

	return 1;
}

void os_mutex_destroy(os_mutex_t* m)
{
	if(m->pPriv) 
	{
		os_mutex_priv_t* priv = (os_mutex_priv_t*) m->pPriv;
		DeleteCriticalSection(priv->hMutex);
		delete priv;
		m->pPriv = NULL;
	}
}

int os_mutex_lock(os_mutex_t* m)
{
	os_mutex_priv_t* priv = (os_mutex_priv_t*) m->pPriv;
	if(!priv) 
		return 0;

	EnterCriticalSection(priv->hMutex);
	return 1;
}

int os_mutex_trylock(os_mutex_t* m)
{
	DWORD  ret ;
	os_mutex_priv_t* priv = (os_mutex_priv_t*) m->pPriv;
	if(!priv) 
		return 0;

	if (TryEnterCriticalSection(priv->hMutex) == FALSE)
        return 0;

    LeaveCriticalSection(priv->hMutex);
    return 1;
}

void os_mutex_unlock(os_mutex_t* m)
{
	os_mutex_priv_t* priv = (os_mutex_priv_t*) m->pPriv;
	if(!priv) 
		return;

	LeaveCriticalSection(priv->hMutex);
}

#endif

